<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { CourseItem } from '@/types/course';
  import { getCourseList } from '@/api/game';
  import { addOperatorCourse } from '@/api/operator';
  import { Message } from '@arco-design/web-vue';

  const props = defineProps<{
    operatorId: string;
    excludeIds: string[];
  }>();

  const emit = defineEmits(['close']);

  const courseId = ref('');
  const courseList = ref<CourseItem[]>([]);
  const handleSearchCourse = async (value: string) => {
    try {
      const res = await getCourseList({
        pageIndex: 1,
        pageSize: 50,
        status: [2],
        content: value,
      });
      courseList.value = (res.data.data.list || []).filter(
        (i) => !props.excludeIds.includes(i.id as string)
      );
    } finally {
      // do nothing
    }
  };
  onMounted(() => {
    handleSearchCourse('');
  });

  const saving = ref(false);
  const handleSubmit = async () => {
    if (courseId.value) {
      try {
        saving.value = true;
        await addOperatorCourse(props.operatorId, courseId.value);
        Message.success('操作成功');
        emit('close', true);
      } finally {
        saving.value = false;
      }
    } else {
      Message.warning('请选择合作的球场');
    }
  };
</script>

<template>
  <a-modal
    title="添加合作球场"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-select
      v-model="courseId"
      allow-search
      placeholder="请选择合作球场（可搜索球场名称）"
      :options="
        courseList.map((i) => ({
          label: i.name,
          value: i.id,
        }))
      "
      @search="handleSearchCourse"
    ></a-select>
  </a-modal>
</template>
